package com.ylbh.modules.accessory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylbh.common.pojo.goods.dto.GoodsDTO;
import com.ylbh.common.pojo.goods.dto.GoodsImgDTO;
import com.ylbh.common.pojo.goods.dto.SpecPropertyDTO;
import com.ylbh.common.pojo.goodsorder.vo.LogisticsInformationVO;
import com.ylbh.common.pojo.goodsorder.vo.OrderDetailsVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.accessory.entity.HNGoodsPrice;
import com.ylbh.modules.accessory.service.HLGoodsService;
import com.ylbh.modules.goods.service.GoodsSpecService;
import com.ylbh.modules.goods.service.ShoppingGoodsService;
import com.ylbh.modules.goodsorder.service.ShoppingOrderFormService;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author: czx
 * @date: 2019/11/09 10:21
 */
@RestController
public class HouNiaoController {

    private final Logger log = LoggerFactory.getLogger(HouNiaoController.class);
    // 正式
    private static final String CLIENTID = "14485";

    private static final String CLIENTTOKEN = "F56msDSaaOsEvp57M2ooubckB1gPnIhN";

    // 测试
//    private static final String CLIENTID = "5483";
//    private static final String CLIENTTOKEN = "e93c665855f5af26aecc50b243a8c29c";

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private ShoppingGoodsService shoppingGoodsService;

    @Autowired
    private HLGoodsService hlGoodsService;

    @Autowired
    private ShoppingOrderFormService shoppingOrderFormService;

    public static void main(String[] args) {
//        // 获取规格信息的数值 正则表达式，用于匹配非数字串，+号用于匹配出多个非数字串
//        String regEx = "[^0-9]+";
//        Pattern pattern = Pattern.compile(regEx);
//// 用定义好的正则表达式拆分字符串，把字符串中的数字留出来
//        String[] cs = pattern.split("23我的");
//        String json = "";
//        if (cs.length > 0) {
//            json = cs.length > 1 ? cs[1] : Integer.valueOf(cs[0]).toString();
//        } else {
//
//        }
//        System.out.println(json);
    }

    @GetMapping("/hl/addHouNiaoGoods")
    public CommonResult addHouNiaoGoods() {
        HashMap<String, String> mclsss = new HashMap<>();
        mclsss.put("clientId", CLIENTID);
        mclsss.put("clientToken", CLIENTTOKEN);
        // 获取商品分类
        mclsss.put("method","base.getCategory");
        String getCategory = HttpUtils.sendPost("http://www.houniao.hk/api/route", mclsss);
        org.json.JSONObject jsono = new org.json.JSONObject(getCategory);
        Object oneData = jsono.get("data");
        List<HLVO> hlvos = FastJsonUtil.toList(oneData.toString(), HLVO.class);
        for (int o = 0; o < hlvos.size(); o++) {
            for (int p = 0; p < hlvos.get(o).getChildren().size(); p++) {
                for (int k = 0; k < hlvos.get(o).getChildren().get(p).getChildren().size(); k++) {
                    System.out.println("候鸟分类id:" +hlvos.get(o).getChildren().get(p).getChildren().get(k).getCatId());
                    int hnId = Integer.parseInt(hlvos.get(o).getChildren().get(p).getChildren().get(k).getCatId());
                    if ( hnId != 244) { //144 250
                        Integer newId = HouNiaoClass.getNewId(Integer.parseInt(hlvos.get(o).getChildren().get(p).getChildren().get(k).getCatId()));
                        if (null != newId) {
                            int count = 1;

                            // 查询出这个分类的商品数据，并计算出分页数量
                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("clientToken", CLIENTTOKEN);
                            hashMap.put("clientId", CLIENTID);
                            hashMap.put("method", "goods.getGoodsListByCategoryId");
                            hashMap.put("categoryId", hlvos.get(o).getChildren().get(p).getChildren().get(k).getCatId());
                            hashMap.put("page", "1");
                            String ss = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap);
                            com.alibaba.fastjson.JSONObject fastJson = JSON.parseObject(ss);
                            JSONObject hnData = fastJson.getJSONObject("data");
                            if (null != hnData) {
                                Object num = JSONObject.parseObject(hnData.toString()).get("total");
                                if (null != num && Integer.parseInt(num.toString()) > 50) {
                                    count = new Double(Math.floor(Double.parseDouble(num.toString()) / 50)).intValue();
                                }

                                if (count >= 1) {
                                    for (int i = 1; i <= count + 1; i++) {
                                        HashMap<String, String> m = new HashMap<>();
                                        m.put("clientId", CLIENTID);
                                        m.put("clientToken", CLIENTTOKEN);

                                        // 获取商品列表1
                                        m.put("method", "goods.getGoodsListByCategoryId");
                                        m.put("page", i + "");
                                        m.put("categoryId", hlvos.get(o).getChildren().get(p).getChildren().get(k).getCatId());
                                        String sss = HttpUtils.sendPost("http://www.houniao.hk/api/route", m);
                                        com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(sss);
                                        JSONObject data = jsonObject1.getJSONObject("data");
                                        Object total = JSONObject.parseObject(data.toString()).get("total");
                                        if (Integer.parseInt(total.toString()) > 0 && Integer.parseInt(total.toString()) <= 50) {
                                            count = new Double(Math.floor(Double.parseDouble(total.toString()) / 50)).intValue();
                                        }
                                        String goodsList = data.getString("goodsList");
                                        List<HouNiao> houNiaos = FastJsonUtil.toList(goodsList, HouNiao.class);
                                        for (HouNiao hn : houNiaos) {
                                            //只要上架的商品
                                            if (hn.getIsSale() == 1) {
                                                // 查询该商品是否添加过
                                                int isSku = shoppingGoodsService.selectSku(hn.getSku());
                                                if (isSku == 0) {
                                                    GoodsDTO dto = new GoodsDTO();
                                                    dto.setGoodsSerial(hn.getSku());
                                                    dto.setGoodsName(hn.getGoodsName());
                                                    dto.setGcId(newId);
                                                    JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
                                                    String hnSpec = "";
                                                    for (Map.Entry<String, Object> entry : spec.entrySet()) {
                                                        hnSpec = entry.getKey();
                                                        break;
                                                    }
//                                                String specJSONObject = spec.getString("基准");
                                                    String specJSONObject = spec.getString(hnSpec);
                                                    List<Spec> specs = FastJsonUtil.toList(specJSONObject, Spec.class);


                                                    if (null != specs && specs.size() > 0) {
                                                        List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                                                        // 售价
                                                        BigDecimal buyerPrice = null;
                                                        // 利润
//                                                BigDecimal goodsCostingPrice = null;
                                                        // shopping_goods_spec中插入中间规格表信息
                                                        //                            List<Integer> specList = new ArrayList<>();
                                                        // 商品库存
                                                        int stock = 0;
                                                        for (Spec s : specs) {
                                                            // 根据候鸟的规格名去查询数据库中是否存在该规格
                                                            List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                                                            GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                                                            if (specId.size() > 0) {

                                                                // 说明数据库中已然存在同样的规格名
                                                                if (null == specId.get(0)) {
                                                                    return Ref.error("规格id查询是null");
                                                                }
                                                                gidtj.setId(specId.get(0) + "_");

                                                                //                                    specList.add(specId.get(0));
                                                            } else {
                                                                // 否则没有需要新建规格
                                                                SpecPropertyDTO spdto = new SpecPropertyDTO();
                                                                spdto.setSpecId(32797);
                                                                spdto.setName(s.getSpecDesc());
                                                                goodsSpecService.addSpec(spdto, new Date());
                                                                if (null == spdto.getId()) {
                                                                    // 如果插入都没有返回id就去查
                                                                    spdto = goodsSpecService.selectSpecIdByName(spdto);
                                                                    if (null == spdto.getId()) {
                                                                        return Ref.error("规格id新增返回是null");
                                                                    }
                                                                }
                                                                gidtj.setId(spdto.getId() + "_");
                                                                //                                    specList.add(spdto.getId());
                                                            }

                                                            // 取出最小的
                                                            if (null == buyerPrice) {
                                                                buyerPrice = new BigDecimal(s.getSpecPrice());
                                                            } else {
                                                                if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                                                                    buyerPrice = new BigDecimal(s.getSpecPrice());
                                                                }
                                                            }
//                                                    if (null == goodsCostingPrice) {
//                                                        goodsCostingPrice = new BigDecimal(new DecimalFormat("#.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("0.05"))));
//                                                    } else {
//                                                        if (goodsCostingPrice.compareTo(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("0.05"))))) == 1) {
//                                                            goodsCostingPrice = new BigDecimal(new DecimalFormat("#.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("0.05"))));
//                                                        }
//                                                    }
                                                            if (stock == 0) {
                                                                stock = Integer.parseInt(s.getStock());
                                                            }
                                                            gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                                                            gidtj.setPriceType("2");
                                                            gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                                                            gidtj.setBuyerPrice(s.getSpecPrice());
                                                            gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                                                            gidtj.setCount(s.getStock());
                                                            gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                                            gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                                                            gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                                                            gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                                                            gidtj.setStartExpDate(s.getStartExpDate());
                                                            gidtj.setEndExpDate(s.getEndExpDate());
                                                            gidtj.setWeight(s.getWeight());
                                                            list.add(gidtj);

                                                            //                dto.setVipPrice(new BigDecimal(s.getSpecPrice()));
                                                            //                dto.setIntegral(new BigDecimal(s.getSpecPrice()).intValue());
                                                        }
                                                        dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                                                        dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                                                        dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                                                        dto.setGiveIntegralType(1);
                                                        dto.setBuyerPrice(buyerPrice);
                                                        dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                                        dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                                                        dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.25")))));
                                                        dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                                                        dto.setGoodsStatus(1);
                                                        dto.setGoodsTransfee(0);
                                                        dto.setSeoDescription(hn.getGoodsName());
                                                        dto.setSeoKeywords(hn.getGoodsName());
                                                        dto.setStorePrice(buyerPrice);
                                                        dto.setGoodsCurrentPrice(buyerPrice);
                                                        dto.setExpressTransFee(new BigDecimal("0"));
                                                        dto.setGoodsBrief(hn.getGoodsName());
                                                        //            dto.setGoodsMainPhotoId();
                                                        dto.setPriceType("2");
                                                        dto.setGoodsManagerId(101);
                                                        GoodsImgDTO img = new GoodsImgDTO();
                                                        img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

                                                        ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                                                        imgList.add(img);
                                                        dto.setMainImg(imgList);
                                                        imgList.add(img);
                                                        dto.setRollingImg(imgList);
                                                        // 查询出该商品对应的库存
//                                                HashMap<String, String> map = new HashMap<>();
//                                                map.put("clientId", CLIENTID);
//                                                map.put("clientToken", CLIENTTOKEN);
//                                                map.put("goodsSku", hn.getSku());
//                                                map.put("method", "goods.getStock");
//                                                String stock = HttpUtils.sendPost("http://www.houniao.hk/api/route", map);
//                                                System.out.println(hn.getSku());
//                                                org.json.JSONObject jsonObject = new org.json.JSONObject(stock);
//                                                Object data1 = jsonObject.get("data");
//                                                List<StockNum> stockNums = FastJsonUtil.toList(data1.toString(), StockNum.class);
//                                                if (stockNums.size() > 0)
//                                                    dto.setGoodsInventory(Integer.parseInt(stockNums.get(0).getStockNum()));
                                                        dto.setGoodsInventory(stock);
                                                        if (!StringUtils.isEmpty(hn.getDescription())) {
                                                            dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                                                            dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                                                            dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                                                            dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                                                            String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                                                            dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
                                                            //                        dto.setGoodsDetails(hn.getDescription().replace("&lt;p&gt;&lt;", "<p><"));
                                                            //                        dto.setGoodsDetails(dto.getGoodsDetails().replace("title=&quot;", "title=\""));
                                                            //                        dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                                                            //                        dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                                                            //                        dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;&lt;", "><"));
                                                            //                        dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;&lt;/p&gt;", "></p>"));
                                                        }
                                                        System.out.println(dto);
                                                        // 商品订阅
                                                        HashMap<String, String> hashMap1 = new HashMap<>();
                                                        hashMap1.put("clientId", CLIENTID);
                                                        hashMap1.put("clientToken", CLIENTTOKEN);
                                                        hashMap1.put("method", "goods.subscribe");
                                                        hashMap1.put("goodsSku", dto.getGoodsSerial());
                                                        String subscribe = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap1);
                                                        dto.setSupplyChainType(1);
                                                        if ("保税".equals(hn.getTradeType())) {
                                                            dto.setTradeType(1);
                                                        } else if ("一般贸易".equals(hn.getTradeType())) {
                                                            dto.setTradeType(2);
                                                        } else if ("国内贸易".equals(hn.getTradeType())) {
                                                            dto.setTradeType(3);
                                                        } else if ("香港直邮".equals(hn.getTradeType())) {
                                                            dto.setTradeType(4);
                                                        } else {
                                                            dto.setTradeType(5);
                                                        }
                                                        HashMap<String, String> mmm = new HashMap<>();
                                                        mmm.put("clientId", CLIENTID);
                                                        mmm.put("clientToken", CLIENTTOKEN);
                                                        mmm.put("goodsSku", dto.getGoodsSerial());
                                                        mmm.put("method", "goods.getPrice");
                                                        String express = HttpUtils.sendPost("http://www.houniao.hk/api/route", mmm);
                                                        com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
                                                        String dataPrice = hnprice.getString("data");
                                                        List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
                                                        for (HNGoodsPrice hngp : hnGoodsPrices) {
                                                            if (hngp.getNoDeliveryArea().size() > 0) {
                                                                String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                                                                noDeliveryArea = noDeliveryArea.replace("[\"", "[");
                                                                noDeliveryArea = noDeliveryArea.replace("\"]", "]");
                                                                noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                                                                dto.setNoDeliveryArea(noDeliveryArea);
                                                            }
                                                        }
//                                                    dto.setNoDeliveryArea(JSON.toJSONString(hnGoodsPrice.getNoDeliveryArea()));
                                                        dto.setOverseasGoods(1);
                                                        System.out.println(subscribe);
                                                        shoppingGoodsService.add(dto, ShiroUtils.getUserId());
                                                        //                            ArrayList<Integer> ridSpecId = new ArrayList<>();
                                                        //                            Set set = new HashSet();
                                                        //                            for (Integer it:specList) {
                                                        //                                if (set.add(it)) {
                                                        //                                    ridSpecId.add(it);
                                                        //                                }
                                                        //                            }
                                                        //                            for (Integer specId : ridSpecId) {
                                                        //                                // 插入商品id与规格和的中间表信息
                                                        //                                goodsSpecService.addGoodsIdOrSpecId(specId, dto.getId());
                                                        //                            }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return Ref.ok();
    }

//    @PostMapping(value = "/hl/hlCallback")
    @RequestMapping(value = "/hl/hlCallback", consumes = "application/x-www-form-urlencoded;charset=UTF-8")
    public String hlCallback(HttpServletRequest request) throws UnsupportedEncodingException {
//        String dataParam = "{data: {\"goodsName\": \"【爱他美】\", \"goodsSku\":\"HN1075540221\"}}";
//        String dataParam = "{\n" +
//                "    \"clientId\": \"\",\n" +
//                "    \"pushTime\": \"2018-08-14 19:25:55\",\n" +
//                "    \"data\": {\n" +
//                "        \"orderNo\": \"2018062746443\",\n" +
//                "        \"expressCode\": \"HTKY\",\n" +
//                "        \"expressName\": \"百世汇通\",\n" +
//                "        \"expressNo\": \"51052017701326\",\n" +
//                "        \"deliveryTime\": \"2018-06-28 09:22:33\",\n" +
//                "        \"goodsSku\": \"HN1075540221\",\n" +
//                "        \"goodsName\": \"【荷兰直邮】德国爱他美奶粉 3 段 800g\",\n" +
//                "        \"goodsSpecGroup\": \"2019年12月\",\n" +
//                "        \"goodsSpecNum\": \"1\",\n" +
//                "        \"goodsNum\": \"1\"\n" +
//                "    }\n" +
//                "}";
//        data.setRequestData(dataParam);
        log.info("================================================================");
//        log.info("候鸟推送通知信息：" + data);
        log.info("================================================================");
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String urlDecoder = URLDecoder.decode(sb.toString(), "UTF-8");
        Map<String, Object> mapResult = JSONObject.parseObject(urlDecoder);
        if (null != mapResult) {
            log.info("URLDecoder解码后数据：" + mapResult);
            String dataSign2 = mapResult.get("dataSign") == null ? "" : mapResult.get("dataSign").toString();
            String dataType2 = mapResult.get("dataType") == null ? "" : mapResult.get("dataType").toString();
            String requestType2 = mapResult.get("requestType") == null ? "" : mapResult.get("requestType").toString();
            String requestData2 = mapResult.get("requestData") == null ? "" : mapResult.get("requestData").toString();
            String clientId2 = mapResult.get("clientId") == null ? "" : mapResult.get("clientId").toString();
            String data2 = mapResult.get("data") == null ? "" : mapResult.get("data").toString();
            String pushTime2 = mapResult.get("pushTime") == null ? "" : mapResult.get("pushTime").toString();
            HNDTO hndto = new HNDTO();
            hndto.setDataSign(dataSign2);
            hndto.setDataType(dataType2);
            hndto.setRequestType(requestType2);
            hndto.setRequestData(requestData2);
            hndto.setClientId(clientId2);
            hndto.setData("{" +data2 + "}");
            hndto.setPushTime(pushTime2);
            hlGoodsService.goodsShelve(hndto);
            return "success";
        }
        return "error";
//        else {
//            HNDTO hndto = new HNDTO();
//            hndto.setDataSign("90EDAACDDD4ED8B1EDD554F5459B9A6F");
//            hndto.setDataType("json");
//            hndto.setRequestType("order.delivery");
//            hndto.setRequestData("{\\\"clientId\\\":\\\"5483\\\",\\\"pushTime\\\":\\\"2019-11-25 15:38:56\\\",\\\"data\\\":{\\\"orderNo\\\":\\\"20191123093934000\\\",\\\"hnOrderNo\\\":\\\"2019112362249\\\",\\\"expressCode\\\":\\\"ems\\\",\\\"expressName\\\":\\\"EMS\\\",\\\"expressNo\\\":\\\"69663333\\\",\\\"deliveryTime\\\":\\\"2019-11-25 15:23:19\\\",\\\"goodsSku\\\":\\\"HN1075510089\\\",\\\"goodsName\\\":\\\"\\\\u3010\\\\u9999\\\\u6e2f\\\\u76f4\\\\u90ae\\\\u3011\\\\u8d44\\\\u751f\\\\u5802UNO\\\\u7537\\\\u58eb\\\\u6d17\\\\u9762\\\\u5976130g\\\\uff08\\\\u7eff\\\\u8272\\\\u7f8e\\\\u767d\\\\u4fdd\\\\u6e7f\\\\uff09\\\",\\\"goodsSpecGroup\\\":\\\"\\\",\\\"goodsSpecNum\\\":\\\"1\\\",\\\"goodsNum\\\":\\\"1\\\",\\\"type\\\":\\\"edit\\\"}}");
//            hndto.setClientId("5483");
//            hndto.setData("{\"orderNo\": \"20191123202919034\",\n" +
//                    "\t\t\"hnOrderNo\": \"2019112362270\",\n" +
//                    "\t\t\"expressCode\": \"zjs\",\n" +
//                    "\t\t\"expressName\": \"宅急送\",\n" +
//                    "\t\t\"expressNo\": \"69663333\",\n" +
//                    "\t\t\"deliveryTime\": \"2019-11-25 15:23:19\",\n" +
//                    "\t\t\"goodsSku\": \"HN1075510089\",\n" +
//                    "\t\t\"goodsName\": \"\\u3010\\u9999\\u6e2f\\u76f4\\u90ae\\u3011\\u8d44\\u751f\\u5802UNO\\u7537\\u58eb\\u6d17\\u9762\\u5976130g\\uff08\\u7eff\\u8272\\u7f8e\\u767d\\u4fdd\\u6e7f\\uff09\",\n" +
//                    "\t\t\"goodsSpecGroup\": \"\",\n" +
//                    "\t\t\"goodsSpecNum\": \"1\",\n" +
//                    "\t\t\"goodsNum\": \"1\",\n" +
//                    "\t\t\"type\": \"edit\"}");
//            hndto.setPushTime("2019-11-25 15:38:56");
//            hlGoodsService.goodsShelve(hndto);
//            return "error";
//        }
    }

    @GetMapping("/hn/getHNBySku")
    public CommonResult getHNBySku(@RequestParam String sku) {
        HashMap<String, String> m = new HashMap<>();
        m.put("clientId", CLIENTID);
        m.put("clientToken", CLIENTTOKEN);
        m.put("method", "goods.getGoodsDetailBySku");
        m.put("goodsSku", sku);
        String sss = HttpUtils.sendPost("http://www.houniao.hk/api/route", m);
        org.json.JSONObject jsonNo = new org.json.JSONObject(sss);
        Object oneData = jsonNo.get("data");
        return Ref.ok(oneData);
    }

    @GetMapping("hn/modifyGoodsDetailsBySku")
    public CommonResult modifyGoodsDetailsBySku(@RequestParam String sku) {
        HashMap<String, String> m = new HashMap<>();
        m.put("clientId", CLIENTID);
        m.put("clientToken", CLIENTTOKEN);
        m.put("method", "goods.getGoodsDetailBySku");
//            m.put("page", "1");
        m.put("goodsSku", sku);
        String sss = HttpUtils.sendPost("http://www.houniao.hk/api/route", m);
        org.json.JSONObject jsono = new org.json.JSONObject(sss);
        Object oneData = jsono.get("data");
        org.json.JSONObject goodList = new org.json.JSONObject(oneData.toString());
        Object goodsList1 = goodList.get("goodsDetail");
        List<HouNiao> houNiaos = FastJsonUtil.toList("[" + goodsList1.toString() + "]", HouNiao.class);
        for (HouNiao hn : houNiaos) {
            GoodsDTO dto = new GoodsDTO();
            //只要上架的商品
            if (!StringUtils.isEmpty(hn.getDescription())) {
                dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
            }
            dto.setGoodsSerial(hn.getSku());
            // 修改商品展示详情
            shoppingGoodsService.updateGoodsDetailsBySku(dto);

        }
        return Ref.ok();
    }

    @GetMapping("/hl/addHouNiaoGoodsBySku")
    public CommonResult mm(@RequestParam String skuList, @RequestParam Integer gcId) {
//        String skuList ="HN10755800747, HN10755800746, HN10755800748";
        String[] skuLength = skuList.split(",");
        for (int i = 0; i < skuLength.length; i++) {
            HashMap<String, String> m = new HashMap<>();
            m.put("clientId", CLIENTID);
            m.put("clientToken", CLIENTTOKEN);

            // 获取商品列表1
            m.put("method", "goods.getGoodsDetailBySku");
//            m.put("page", "1");
            m.put("goodsSku", skuLength[i]);
            String sss = HttpUtils.sendPost("http://www.houniao.hk/api/route", m);
            org.json.JSONObject jsono = new org.json.JSONObject(sss);
            Object oneData = jsono.get("data");
            org.json.JSONObject goodList = new org.json.JSONObject(oneData.toString());
            Object goodsList1 = goodList.get("goodsDetail");
            List<HouNiao> houNiaos = FastJsonUtil.toList("[" + goodsList1.toString() + "]", HouNiao.class);
            for (HouNiao hn : houNiaos) {
                //只要上架的商品
                if (hn.getIsSale() == 1) {
                    // 查询该商品是否添加过
                    int isSku = shoppingGoodsService.selectSku(hn.getSku());
                    if (isSku == 0) {
                        GoodsDTO dto = new GoodsDTO();
                        dto.setGoodsSerial(hn.getSku());
                        dto.setGoodsName(hn.getGoodsName());
//                        Integer newId = HouNiaoClass.getNewId(Integer.parseInt(hn.getCategoryId()));
//                        newId = 579;
                        if (null != gcId) {
                            dto.setGcId(gcId);
                            JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
                            String hnSpec = "";
                            for (Map.Entry<String, Object> entry : spec.entrySet()) {
                                hnSpec = entry.getKey();
                                break;
                            }

                            String specJSONObject = spec.getString(hnSpec);
                            List<Spec> specs = FastJsonUtil.toList(specJSONObject, Spec.class);


                            if (null != specs && specs.size() > 0) {
                                List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                                // 售价
                                BigDecimal buyerPrice = null;
                                // 商品库存
                                int stock = 0;
                                for (Spec s : specs) {
                                    // 根据候鸟的规格名去查询数据库中是否存在该规格
                                    List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                                    GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                                    if (specId.size() > 0) {

                                        // 说明数据库中已然存在同样的规格名
                                        if (null == specId.get(0)) {
                                            return Ref.error("规格id查询是null");
                                        }
                                        gidtj.setId(specId.get(0) + "_");

                                        //                                    specList.add(specId.get(0));
                                    } else {
                                        // 否则没有需要新建规格
                                        SpecPropertyDTO spdto = new SpecPropertyDTO();
                                        spdto.setSpecId(32797);
                                        spdto.setName(s.getSpecDesc());
                                        goodsSpecService.addSpec(spdto, new Date());
                                        if (null == spdto.getId()) {
                                            // 如果插入都没有返回id就去查
                                            spdto = goodsSpecService.selectSpecIdByName(spdto);
                                            if (null == spdto.getId()) {
                                                return Ref.error("规格id新增返回是null");
                                            }
                                        }
                                        gidtj.setId(spdto.getId() + "_");
                                    }

                                    // 取出最小的
                                    if (null == buyerPrice) {
                                        buyerPrice = new BigDecimal(s.getSpecPrice());
                                    } else {
                                        if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                                            buyerPrice = new BigDecimal(s.getSpecPrice());
                                        }
                                    }
                                    if (stock == 0) {
                                        stock = Integer.parseInt(s.getStock());
                                    }
                                    gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                                    gidtj.setPriceType("2");
                                    gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                                    gidtj.setBuyerPrice(s.getSpecPrice());
                                    gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                                    gidtj.setCount(s.getStock());
                                    gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                    gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                                    gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                                    gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                                    gidtj.setStartExpDate(s.getStartExpDate());
                                    gidtj.setEndExpDate(s.getEndExpDate());
                                    gidtj.setWeight(s.getWeight());
                                    list.add(gidtj);

                                }
                                dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                                dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                                dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                                dto.setGiveIntegralType(1);
                                dto.setBuyerPrice(buyerPrice);
                                dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                                dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.25")))));
                                dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                                dto.setGoodsStatus(1);
                                dto.setGoodsTransfee(0);
                                dto.setSeoDescription(hn.getGoodsName());
                                dto.setSeoKeywords(hn.getGoodsName());
                                dto.setStorePrice(buyerPrice);
                                dto.setGoodsCurrentPrice(buyerPrice);
                                dto.setExpressTransFee(new BigDecimal("0"));
                                dto.setGoodsBrief(hn.getGoodsName());
                                //            dto.setGoodsMainPhotoId();
                                dto.setPriceType("2");
                                dto.setGoodsManagerId(101);
                                GoodsImgDTO img = new GoodsImgDTO();
                                img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

                                ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                                imgList.add(img);
                                dto.setMainImg(imgList);
                                imgList.add(img);
                                dto.setRollingImg(imgList);
                                // 查询出该商品对应的库存
                                dto.setGoodsInventory(stock);
                                if (!StringUtils.isEmpty(hn.getDescription())) {
                                    dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                                    String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                                    dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
                                }
                                System.out.println(dto);
                                // 商品订阅
                                HashMap<String, String> hashMap1 = new HashMap<>();
                                hashMap1.put("clientId", CLIENTID);
                                hashMap1.put("clientToken", CLIENTTOKEN);
                                hashMap1.put("method", "goods.subscribe");
                                hashMap1.put("goodsSku", dto.getGoodsSerial());
                                String subscribe = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap1);
                                dto.setSupplyChainType(1);
                                if ("保税".equals(hn.getTradeType())) {
                                    dto.setTradeType(1);
                                } else if ("一般贸易".equals(hn.getTradeType())) {
                                    dto.setTradeType(2);
                                } else if ("国内贸易".equals(hn.getTradeType())) {
                                    dto.setTradeType(3);
                                } else if ("香港直邮".equals(hn.getTradeType())) {
                                    dto.setTradeType(4);
                                } else {
                                    dto.setTradeType(5);
                                }
                                HashMap<String, String> mmm = new HashMap<>();
                                mmm.put("clientId", CLIENTID);
                                mmm.put("clientToken", CLIENTTOKEN);
                                mmm.put("goodsSku", dto.getGoodsSerial());
                                mmm.put("method", "goods.getPrice");
                                String express = HttpUtils.sendPost("http://www.houniao.hk/api/route", mmm);
                                com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
                                String dataPrice = hnprice.getString("data");
                                List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
                                for (HNGoodsPrice hngp : hnGoodsPrices) {
                                    if (hngp.getNoDeliveryArea().size() > 0) {
                                        String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                                        noDeliveryArea = noDeliveryArea.replace("[\"", "[");
                                        noDeliveryArea = noDeliveryArea.replace("\"]", "]");
                                        noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                                        dto.setNoDeliveryArea(noDeliveryArea);
                                    }
                                }
                                dto.setOverseasGoods(1);
                                System.out.println(subscribe);
                                shoppingGoodsService.add(dto, ShiroUtils.getUserId());
                            }
                        }
                    }
                }

            }
        }
        return Ref.ok();
    }

    @ApiOperation("获取候鸟的所有商品列表")
    @GetMapping("getHNGoodsList")
    public CommonResult getHNGoodsList() {

        HashMap<String, String> p = new HashMap<>();
        p.put("clientId", CLIENTID);
        p.put("clientToken", CLIENTTOKEN);
        p.put("method", "base.getCategory");
        String getCategory = HttpUtils.sendPost("http://www.houniao.hk/api/route", p);
        org.json.JSONObject categoryJson = new org.json.JSONObject(getCategory);
        Object categoryData = categoryJson.get("data");
        List<HLVO> hlvos = FastJsonUtil.toList(categoryData.toString(), HLVO.class);

        for (int i = 1; i < 345; i++) {
            HashMap<String, String> map = new HashMap<>();
            map.put("clientId", CLIENTID);
            map.put("clientToken", CLIENTTOKEN);
            map.put("page", i+"");
            map.put("method", "goods.goodsList");
            String goodsList = HttpUtils.sendPost("http://www.houniao.hk/api/route", map);
            org.json.JSONObject jsono = new org.json.JSONObject(goodsList);
            Object oneData = jsono.get("data");
            org.json.JSONObject goodList = new org.json.JSONObject(oneData.toString());
            Object goodsList1 = goodList.get("goodsList");
            List<HouNiao> houNiaos = FastJsonUtil.toList(goodsList1.toString(), HouNiao.class);
            for (HouNiao hn : houNiaos) {
                if (hn.getIsSale() == 1) {
                    // 查询该商品是否添加过
                    int isSku = shoppingGoodsService.selectSku(hn.getSku());
                    if (isSku == 0 && !"HN1075501270".equals(hn.getSku()) && !"HN1075511066".equals(hn.getSku()) && !"HN1075530423".equals(hn.getSku()) && !"HN10755010616".equals(hn.getSku()) && !"HN10755010609".equals(hn.getSku()) && !"HN1075504951".equals(hn.getSku()) && !"HN1075505443".equals(hn.getSku()) && !"HN1075521758".equals(hn.getSku()) && !"HN10755010472".equals(hn.getSku()) && !"HN10755301596".equals(hn.getSku())) {
                        GoodsDTO dto = new GoodsDTO();
                        dto.setGoodsSerial(hn.getSku());
                        dto.setGoodsName(hn.getGoodsName());
                        Integer newId = HouNiaoClass.getNewId(Integer.parseInt(hn.getCategoryId()));
                        if (null != newId) {
                            dto.setGcId(newId);
                            JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
                            String hnSpec = "";
                            for (Map.Entry<String, Object> entry : spec.entrySet()) {
                                hnSpec = entry.getKey();
                                break;
                            }

                            String specJSONObject = spec.getString(hnSpec);
                            List<Spec> specs = FastJsonUtil.toList(specJSONObject, Spec.class);


                            if (null != specs && specs.size() > 0) {
                                List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                                // 售价
                                BigDecimal buyerPrice = null;
                                // 商品库存
                                int stock = 0;
                                for (Spec s : specs) {
                                    // 根据候鸟的规格名去查询数据库中是否存在该规格
                                    List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                                    GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                                    if (specId.size() > 0) {

                                        // 说明数据库中已然存在同样的规格名
                                        if (null == specId.get(0)) {
                                            return Ref.error("规格id查询是null");
                                        }
                                        gidtj.setId(specId.get(0) + "_");

                                        //                                    specList.add(specId.get(0));
                                    } else {
                                        // 否则没有需要新建规格
                                        SpecPropertyDTO spdto = new SpecPropertyDTO();
                                        spdto.setSpecId(32797);
                                        spdto.setName(s.getSpecDesc());
                                        goodsSpecService.addSpec(spdto, new Date());
                                        if (null == spdto.getId()) {
                                            // 如果插入都没有返回id就去查
                                            spdto = goodsSpecService.selectSpecIdByName(spdto);
                                            if (null == spdto.getId()) {
                                                return Ref.error("规格id新增返回是null");
                                            }
                                        }
                                        gidtj.setId(spdto.getId() + "_");
                                    }

                                    // 取出最小的
                                    if (null == buyerPrice) {
                                        buyerPrice = new BigDecimal(s.getSpecPrice());
                                    } else {
                                        if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                                            buyerPrice = new BigDecimal(s.getSpecPrice());
                                        }
                                    }
                                    if (stock == 0) {
                                        stock = Integer.parseInt(s.getStock());
                                    }
                                    gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                                    gidtj.setPriceType("2");
                                    gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                                    gidtj.setBuyerPrice(s.getSpecPrice());
                                    gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                                    gidtj.setCount(s.getStock());
                                    gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                    gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                                    gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                                    gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                                    gidtj.setStartExpDate(s.getStartExpDate());
                                    gidtj.setEndExpDate(s.getEndExpDate());
                                    gidtj.setWeight(s.getWeight());
                                    list.add(gidtj);

                                }
                                dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                                dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                                dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                                dto.setGiveIntegralType(1);
                                dto.setBuyerPrice(buyerPrice);
                                dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                                dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.25")))));
                                dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                                dto.setGoodsStatus(1);
                                dto.setGoodsTransfee(0);
                                dto.setSeoDescription(hn.getGoodsName());
                                dto.setSeoKeywords(hn.getGoodsName());
                                dto.setStorePrice(buyerPrice);
                                dto.setGoodsCurrentPrice(buyerPrice);
                                dto.setExpressTransFee(new BigDecimal("0"));
                                dto.setGoodsBrief(hn.getGoodsName());
                                //            dto.setGoodsMainPhotoId();
                                dto.setPriceType("2");
                                dto.setGoodsManagerId(101);
                                GoodsImgDTO img = new GoodsImgDTO();
                                img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

                                ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                                imgList.add(img);
                                dto.setMainImg(imgList);
                                imgList.add(img);
                                dto.setRollingImg(imgList);
                                // 查询出该商品对应的库存
                                dto.setGoodsInventory(stock);
                                if (!StringUtils.isEmpty(hn.getDescription())) {
                                    dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                                    dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                                    String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                                    dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
                                }
                                System.out.println(dto);
                                // 商品订阅
                                HashMap<String, String> hashMap1 = new HashMap<>();
                                hashMap1.put("clientId", CLIENTID);
                                hashMap1.put("clientToken", CLIENTTOKEN);
                                hashMap1.put("method", "goods.subscribe");
                                hashMap1.put("goodsSku", dto.getGoodsSerial());
                                String subscribe = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap1);
                                dto.setSupplyChainType(1);
                                if ("保税".equals(hn.getTradeType())) {
                                    dto.setTradeType(1);
                                } else if ("一般贸易".equals(hn.getTradeType())) {
                                    dto.setTradeType(2);
                                } else if ("国内贸易".equals(hn.getTradeType())) {
                                    dto.setTradeType(3);
                                } else if ("香港直邮".equals(hn.getTradeType())) {
                                    dto.setTradeType(4);
                                } else {
                                    dto.setTradeType(5);
                                }
                                HashMap<String, String> mmm = new HashMap<>();
                                mmm.put("clientId", CLIENTID);
                                mmm.put("clientToken", CLIENTTOKEN);
                                mmm.put("goodsSku", dto.getGoodsSerial());
                                mmm.put("method", "goods.getPrice");
                                String express = HttpUtils.sendPost("http://www.houniao.hk/api/route", mmm);
                                com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
                                String dataPrice = hnprice.getString("data");
                                List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
                                for (HNGoodsPrice hngp : hnGoodsPrices) {
                                    if (hngp.getNoDeliveryArea().size() > 0) {
                                        String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                                        noDeliveryArea = noDeliveryArea.replace("[\"", "[");
                                        noDeliveryArea = noDeliveryArea.replace("\"]", "]");
                                        noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                                        dto.setNoDeliveryArea(noDeliveryArea);
                                    }
                                }
                                dto.setOverseasGoods(1);
                                System.out.println(subscribe);
                                shoppingGoodsService.add(dto, ShiroUtils.getUserId());
                            }
                        } else {
                            System.out.println("未匹配到id" + Integer.parseInt(hn.getCategoryId()));
                        }
                    }
                }
            }
        }
        return Ref.ok();
    }

    @RequestMapping("hn/uploadCategoryId")
    public CommonResult uploadCategoryId() {
        List<Integer> integers = new ArrayList<>();
        integers.add(923);
        integers.add(924);
        integers.add(925);
        integers.add(926);
        integers.add(927);
        integers.add(928);
        integers.add(929);
        integers.add(930);
        integers.add(931);
        integers.add(932);
        integers.add(933);
        integers.add(584);
        integers.add(847);
        for (int d = 0; d < integers.size(); d++) {
            Integer newId = HouNiaoClass.getNewId(integers.get(d));
            if (null != newId) {
                int count = 1;
                // 查询出这个分类的商品数据，并计算出分页数量
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("clientToken", CLIENTTOKEN);
                hashMap.put("clientId", CLIENTID);
                hashMap.put("method", "goods.getGoodsListByCategoryId");
                hashMap.put("categoryId", integers.get(d) + "");
                hashMap.put("page", "1");
                String ss = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap);
                com.alibaba.fastjson.JSONObject fastJson = JSON.parseObject(ss);
                JSONObject hnData = fastJson.getJSONObject("data");
                if (null != hnData) {
                    Object num = JSONObject.parseObject(hnData.toString()).get("total");
                    if (null != num && Integer.parseInt(num.toString()) > 50) {
                        count = new Double(Math.floor(Double.parseDouble(num.toString()) / 50)).intValue();
                    }

                    if (count >= 1) {
                        for (int i = 1; i <= count + 1; i++) {
                            HashMap<String, String> m = new HashMap<>();
                            m.put("clientId", CLIENTID);
                            m.put("clientToken", CLIENTTOKEN);

                            // 获取商品列表1
                            m.put("method", "goods.getGoodsListByCategoryId");
                            m.put("page", i + "");
                            m.put("categoryId", integers.get(d) + "");
                            String sss = HttpUtils.sendPost("http://www.houniao.hk/api/route", m);
                            com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(sss);
                            JSONObject data = jsonObject1.getJSONObject("data");
                            Object total = JSONObject.parseObject(data.toString()).get("total");
                            if (Integer.parseInt(total.toString()) > 0 && Integer.parseInt(total.toString()) <= 50) {
                                count = new Double(Math.floor(Double.parseDouble(total.toString()) / 50)).intValue();
                            }
                            String goodsList = data.getString("goodsList");
                            List<HouNiao> houNiaos = FastJsonUtil.toList(goodsList, HouNiao.class);
                            for (HouNiao hn : houNiaos) {
                                //只要上架的商品
                                if (hn.getIsSale() == 1) {
                                    // 查询该商品是否添加过
                                    int isSku = shoppingGoodsService.selectSku(hn.getSku());
                                    if (isSku == 0) {
                                        GoodsDTO dto = new GoodsDTO();
                                        dto.setGoodsSerial(hn.getSku());
                                        dto.setGoodsName(hn.getGoodsName());
                                        dto.setGcId(newId);
                                        JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
                                        String hnSpec = "";
                                        for (Map.Entry<String, Object> entry : spec.entrySet()) {
                                            hnSpec = entry.getKey();
                                            break;
                                        }
//                                                String specJSONObject = spec.getString("基准");
                                        String specJSONObject = spec.getString(hnSpec);
                                        List<Spec> specs = FastJsonUtil.toList(specJSONObject, Spec.class);


                                        if (null != specs && specs.size() > 0) {
                                            List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                                            // 售价
                                            BigDecimal buyerPrice = null;
                                            // 利润
                                            // 商品库存
                                            int stock = 0;
                                            for (Spec s : specs) {
                                                // 根据候鸟的规格名去查询数据库中是否存在该规格
                                                List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                                                GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                                                if (specId.size() > 0) {

                                                    // 说明数据库中已然存在同样的规格名
                                                    if (null == specId.get(0)) {
                                                        return Ref.error("规格id查询是null");
                                                    }
                                                    gidtj.setId(specId.get(0) + "_");

                                                    //                                    specList.add(specId.get(0));
                                                } else {
                                                    // 否则没有需要新建规格
                                                    SpecPropertyDTO spdto = new SpecPropertyDTO();
                                                    spdto.setSpecId(32797);
                                                    spdto.setName(s.getSpecDesc());
                                                    goodsSpecService.addSpec(spdto, new Date());
                                                    if (null == spdto.getId()) {
                                                        // 如果插入都没有返回id就去查
                                                        spdto = goodsSpecService.selectSpecIdByName(spdto);
                                                        if (null == spdto.getId()) {
                                                            return Ref.error("规格id新增返回是null");
                                                        }
                                                    }
                                                    gidtj.setId(spdto.getId() + "_");
                                                }

                                                // 取出最小的
                                                if (null == buyerPrice) {
                                                    buyerPrice = new BigDecimal(s.getSpecPrice());
                                                } else {
                                                    if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                                                        buyerPrice = new BigDecimal(s.getSpecPrice());
                                                    }
                                                }
                                                if (stock == 0) {
                                                    stock = Integer.parseInt(s.getStock());
                                                }
                                                gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                                                gidtj.setPriceType("2");
                                                gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                                                gidtj.setBuyerPrice(s.getSpecPrice());
                                                gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                                                gidtj.setCount(s.getStock());
                                                gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                                gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                                                gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                                                gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                                                gidtj.setStartExpDate(s.getStartExpDate());
                                                gidtj.setEndExpDate(s.getEndExpDate());
                                                gidtj.setWeight(s.getWeight());
                                                list.add(gidtj);
                                            }
                                            dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                                            dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                                            dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                                            dto.setGiveIntegralType(1);
                                            dto.setBuyerPrice(buyerPrice);
                                            dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                                            dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                                            dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.25")))));
                                            dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                                            dto.setGoodsStatus(1);
                                            dto.setGoodsTransfee(0);
                                            dto.setSeoDescription(hn.getGoodsName());
                                            dto.setSeoKeywords(hn.getGoodsName());
                                            dto.setStorePrice(buyerPrice);
                                            dto.setGoodsCurrentPrice(buyerPrice);
                                            dto.setExpressTransFee(new BigDecimal("0"));
                                            dto.setGoodsBrief(hn.getGoodsName());
                                            //            dto.setGoodsMainPhotoId();
                                            dto.setPriceType("2");
                                            dto.setGoodsManagerId(101);
                                            GoodsImgDTO img = new GoodsImgDTO();
                                            img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

                                            ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                                            imgList.add(img);
                                            dto.setMainImg(imgList);
                                            imgList.add(img);
                                            dto.setRollingImg(imgList);
                                            dto.setGoodsInventory(stock);
                                            if (!StringUtils.isEmpty(hn.getDescription())) {
                                                dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                                                dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                                                dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                                                dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                                                String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                                                dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
                                            }
                                            System.out.println(dto);
                                            // 商品订阅
                                            HashMap<String, String> hashMap1 = new HashMap<>();
                                            hashMap1.put("clientId", CLIENTID);
                                            hashMap1.put("clientToken", CLIENTTOKEN);
                                            hashMap1.put("method", "goods.subscribe");
                                            hashMap1.put("goodsSku", dto.getGoodsSerial());
                                            String subscribe = HttpUtils.sendPost("http://www.houniao.hk/api/route", hashMap1);
                                            dto.setSupplyChainType(1);
                                            if ("保税".equals(hn.getTradeType())) {
                                                dto.setTradeType(1);
                                            } else if ("一般贸易".equals(hn.getTradeType())) {
                                                dto.setTradeType(2);
                                            } else if ("国内贸易".equals(hn.getTradeType())) {
                                                dto.setTradeType(3);
                                            } else if ("香港直邮".equals(hn.getTradeType())) {
                                                dto.setTradeType(4);
                                            } else {
                                                dto.setTradeType(5);
                                            }
                                            HashMap<String, String> mmm = new HashMap<>();
                                            mmm.put("clientId", CLIENTID);
                                            mmm.put("clientToken", CLIENTTOKEN);
                                            mmm.put("goodsSku", dto.getGoodsSerial());
                                            mmm.put("method", "goods.getPrice");
                                            String express = HttpUtils.sendPost("http://www.houniao.hk/api/route", mmm);
                                            com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
                                            String dataPrice = hnprice.getString("data");
                                            List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
                                            for (HNGoodsPrice hngp : hnGoodsPrices) {
                                                if (hngp.getNoDeliveryArea().size() > 0) {
                                                    String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                                                    noDeliveryArea = noDeliveryArea.replace("[\"", "[");
                                                    noDeliveryArea = noDeliveryArea.replace("\"]", "]");
                                                    noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                                                    dto.setNoDeliveryArea(noDeliveryArea);
                                                }
                                            }
//                                                    dto.setNoDeliveryArea(JSON.toJSONString(hnGoodsPrice.getNoDeliveryArea()));
                                            dto.setOverseasGoods(1);
                                            System.out.println(subscribe);
                                            shoppingGoodsService.add(dto, ShiroUtils.getUserId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return Ref.ok();
    }

    @ApiOperation("商城订单详情")
    @GetMapping("/getOrderById")
    public CommonResult getOrderById(@RequestParam String orderId){
        OrderDetailsVO vo = shoppingOrderFormService.getOrderById(orderId);
        return Ref.ok(vo);
    }

    @ApiOperation("查看物流")
    @GetMapping("/getLogisticsInformationByExpressNo")
    public CommonResult<LogisticsInformationVO> getLogisticsInformationByExpressNo(@RequestParam String shipCode) throws Exception{
        LogisticsInformationVO vo = shoppingOrderFormService.getLogisticsInformationByExpressNo(shipCode);
        return Ref.ok(vo);
    }

    @GetMapping("modifyHNGoods")
    public CommonResult modifyHNGoods() {
        hlGoodsService.modifyHNGoods();
        return Ref.ok();
    }

    @GetMapping("modifyHNGoodsPriceOrCount")
    public CommonResult modifyHNGoodsPriceOrCount() {
        String msg = hlGoodsService.modifyHNGoodsPriceOrCount();
        return Ref.ok(msg);
    }
}
